package com.service;

import com.domain.User;
import com.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

//    @Cacheable(cacheNames = "User")
    @Cacheable(cacheNames = "User", unless = "#result==null")
    public User findById(int user_id) {
        Optional<User> optional = userRepository.findById(user_id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }
    //查询所有用户
    @Cacheable(cacheNames = "User")
    public List<User> getUserList() {
        return userRepository.findAll();
    }
    //更新详细用户信息
    @CachePut(cacheNames = "User", key = "#result.id")
    public User updateUser(User user) {
        userRepository.updateUser(user.getId(), user.getPwd());
        return user;
    }
    //删除用户信息
    @CacheEvict(cacheNames = "User")
    public void deleteUser(int user_id) {
        userRepository.deleteById(user_id);
    }

}
